package com.example.servlet.user;

import com.example.entity.*;
import com.example.service.OperationService;
import com.example.service.impl.OperationServiceImpl;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/user_reschedule")
public class uRescheduleServlet extends HttpServlet {
    private OperationService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new OperationServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }
    public static String extractAirportCode(String airportInfo) {
        Pattern pattern = Pattern.compile("\\((.*?)\\)");
        Matcher matcher = pattern.matcher(airportInfo);
        if (matcher.find()) {
            return matcher.group(1); // 返回括号中的内容
        }
        return null; // 如果没有匹配到，返回 null
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        String fid = req.getParameter("f_id");
        String ticketId = req.getParameter("ticketId");
        String paymentMethod = req.getParameter("payment");
        int t_id = Integer.parseInt(ticketId);
        Ticket ticket = service.getTicketById(t_id);
        Order order = service.getOrderById(ticket.getOrder_id());
        User orderUser = service.getUserById(order.getUserId());
        try {
            if (fid != null) {
                int f_id = Integer.parseInt(fid);
                if(ticket.getFlightNo()==f_id){
                    req.getSession().setAttribute("reschedule_same", new Object());
                    resp.sendRedirect("user_reschedule_result?ticketId="+ticketId);
                    return;
                }
                double price1 = ticket.getPrice();
                double price2;
                System.out.println(0);
                if (Objects.equals(ticket.getSeat_type(), "经济舱")) {
                    price2 = service.getFlightById(f_id).getEconomy_price();
                    if (service.addEconomySpaceByFid(f_id) == 0) {
                        throw new Exception("Failed to add economy space");
                    }
                } else if (Objects.equals(ticket.getSeat_type(), "商务舱")) {
                    price2 = service.getFlightById(f_id).getBusiness_price();
                    if (service.addBusinessSpaceByFid(f_id) == 0) {
                        throw new Exception("Failed to add business space");
                    }
                } else {
                    price2 = service.getFlightById(f_id).getFirst_price();
                    if (service.addFirstSpaceByFid(f_id) == 0) {
                        throw new Exception("Failed to add first space");
                    }
                }
                System.out.println(1);
                if(service.refundMoneyByUserIDtypeAndIDcard(orderUser.getID_type(), orderUser.getID_card(), price1)==0){
                    System.out.println(2);
                    throw new Exception("Failed to refund money");
                }
                if(service.deleteTicket(t_id)==0){
                    System.out.println(3);
                    throw new Exception("Failed to delete ticket");
                }
                System.out.println(4);
                if(Objects.equals(ticket.getSeat_type(), "经济舱")){
                    if(service.reduceEconomySpaceByFid(f_id)==0){
                        throw new Exception("Failed to reduce economy space");
                    }
                } else if (Objects.equals(ticket.getSeat_type(),"商务舱")) {
                    if(service.reduceBusinessSpaceByFid(f_id)==0){
                        throw new Exception("Failed to reduce business space");
                    }
                }else{
                    if(service.reduceFirstSpaceByFid(f_id)==0){
                        throw new Exception("Failed to reduce first space");
                    }
                }
                LocalDateTime now = LocalDateTime.now();  // 获取当前时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  // 定义格式化模板
                String formattedNow = now.format(formatter);  // 格式化时间
                System.out.println("当前时间：" + formattedNow);
                Flight flight = service.getFlightById(f_id);
                FlightStatus flightStatus = service.getFlightStatusById(f_id);
                if(service.addOrder(user.getU_id(), user.getU_name(), f_id, flight.getF_airline(), formattedNow, flight.getDeparture_city()+" ("+extractAirportCode(flight.getDeparture_airport())+")", flight.getArrival_city()+" ("+extractAirportCode(flight.getArrival_airport())+")", flight.getDeparture_time(), flight.getArrival_time(), price2, 1, "paid", "已支付", paymentMethod,  formattedNow)==0){
                    System.out.println(5);
                    throw new Exception("Failed to add order");
                }
                String fsst;
                if(Objects.equals(flightStatus.getStatus(), "计划中")) fsst = "scheduled";
                else if(Objects.equals(flightStatus.getStatus(), "即将起飞")) fsst = "upcoming";
                else fsst = "delay";
                if(service.addTicket(service.getLastOrderId(), ticket.getPassenger_id(), ticket.getPassenger_name(), ticket.getPassenger_type(), f_id, formattedNow, price2, ticket.getSeat_type(), fsst,flightStatus.getStatus())==0){
                    System.out.println(6);
                    throw new Exception("Failed to add ticket");
                }
                if(service.reduceMoneyByUserIDtypeAndIDcard(orderUser.getID_type(), orderUser.getID_card(), price2)==0){
                    System.out.println(7);
                    throw new Exception("Failed to refund money");
                }
                if (service.getPassengersByOrderId(ticket.getOrder_id()) == 1) {
                    if(service.deleteOrder(ticket.getOrder_id())==0){
                        System.out.println(8);
                        throw new Exception("Failed to delete order");
                    }
                } else {
                    if (service.reducePassengerOrderNumByPassengerId(user.getID_type(), user.getID_card()) == 0) {
                        System.out.println(9);
                        throw new Exception("Failed to reduce passenger order num");
                    }
                    if (service.reducePassengerPriceOrder(ticket.getOrder_id(), ticket.getPrice()) == 0) {
                        System.out.println(10);
                        throw new Exception("Failed to reduce passenger price order");
                    }
                }
                service.commit();
                resp.sendRedirect("user_ticket");
            }
        }catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            req.getSession().setAttribute("reschedule_failure", new Object());
            resp.sendRedirect("user_reschedule_result?ticketId="+ticketId);
        }
    }
}
